<template>
  <div class="roles-page">
    <!-- 页面标题和操作 -->
    <div class="page-header">
      <div class="header-left">
        <h1>角色管理</h1>
        <p>管理系统角色和权限配置</p>
      </div>
      <div class="header-right">
        <el-button type="primary" :icon="Plus" @click="handleCreate">
          新增角色
        </el-button>
      </div>
    </div>

    <!-- 搜索和筛选 -->
    <el-card class="search-card" shadow="never">
      <el-form :model="searchForm" :inline="true" class="search-form">
        <el-form-item label="角色名称">
          <el-input
            v-model="searchForm.name"
            placeholder="请输入角色名称"
            clearable
            @keyup.enter="handleSearch"
          />
        </el-form-item>
        <el-form-item label="状态">
          <el-select v-model="searchForm.status" placeholder="请选择状态" clearable>
            <el-option label="全部" value="" />
            <el-option label="启用" value="active" />
            <el-option label="禁用" value="inactive" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" :icon="Search" @click="handleSearch">
            搜索
          </el-button>
          <el-button :icon="Refresh" @click="handleReset">
            重置
          </el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 角色表格 -->
    <el-card class="table-card" shadow="never">
      <template #header>
        <div class="card-header">
          <span>角色列表</span>
          <div class="header-actions">
            <el-button
              type="danger"
              :icon="Delete"
              :disabled="!selectedRoles.length"
              @click="handleBatchDelete"
            >
              批量删除
            </el-button>
            <el-button :icon="Download" @click="handleExport">
              导出
            </el-button>
          </div>
        </div>
      </template>

      <el-table
        ref="tableRef"
        v-loading="loading"
        :data="roles"
        @selection-change="handleSelectionChange"
        stripe
        style="width: 100%"
      >
        <el-table-column type="selection" width="55" />
        <el-table-column prop="id" label="ID" width="80" />
        <el-table-column prop="name" label="角色名称" min-width="150" />
        <el-table-column prop="description" label="描述" min-width="200" />
        <el-table-column label="权限数量" width="100">
          <template #default="{ row }">
            <el-tag type="info" size="small">
              {{ row.permissions.length }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="用户数量" width="100">
          <template #default="{ row }">
            <el-tag type="success" size="small">
              {{ row.user_count }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="状态" width="100">
          <template #default="{ row }">
            <el-switch
              v-model="row.status"
              active-value="active"
              inactive-value="inactive"
              @change="handleStatusChange(row)"
            />
          </template>
        </el-table-column>
        <el-table-column prop="created_at" label="创建时间" width="160">
          <template #default="{ row }">
            {{ formatTime(row.created_at) }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="250" fixed="right">
          <template #default="{ row }">
            <el-button
              type="primary"
              size="small"
              :icon="View"
              @click="handleView(row)"
            >
              查看
            </el-button>
            <el-button
              type="warning"
              size="small"
              :icon="Edit"
              @click="handleEdit(row)"
            >
              编辑
            </el-button>
            <el-button
              type="info"
              size="small"
              :icon="Setting"
              @click="handlePermissions(row)"
            >
              权限
            </el-button>
            <el-button
              type="danger"
              size="small"
              :icon="Delete"
              @click="handleDelete(row)"
            >
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="pagination.page"
          v-model:page-size="pagination.size"
          :total="pagination.total"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handlePageChange"
        />
      </div>
    </el-card>

    <!-- 角色详情对话框 -->
    <el-dialog
      v-model="detailVisible"
      title="角色详情"
      width="700px"
      :before-close="handleCloseDetail"
    >
      <div v-if="currentRole" class="role-detail">
        <el-descriptions :column="2" border>
          <el-descriptions-item label="角色名称">
            {{ currentRole.name }}
          </el-descriptions-item>
          <el-descriptions-item label="状态">
            <el-tag :type="currentRole.status === 'active' ? 'success' : 'danger'">
              {{ currentRole.status === 'active' ? '启用' : '禁用' }}
            </el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="描述" :span="2">
            {{ currentRole.description || '-' }}
          </el-descriptions-item>
          <el-descriptions-item label="权限数量">
            {{ currentRole.permissions.length }}
          </el-descriptions-item>
          <el-descriptions-item label="用户数量">
            {{ currentRole.user_count }}
          </el-descriptions-item>
          <el-descriptions-item label="创建时间" :span="2">
            {{ formatTime(currentRole.created_at) }}
          </el-descriptions-item>
        </el-descriptions>

        <div class="permissions-section">
          <h3>权限列表</h3>
          <el-tree
            :data="permissionTree"
            :props="{ children: 'children', label: 'name' }"
            :default-checked-keys="currentRole.permissions"
            node-key="id"
            show-checkbox
            disabled
            class="permission-tree"
          />
        </div>
      </div>
    </el-dialog>

    <!-- 角色编辑对话框 -->
    <el-dialog
      v-model="editVisible"
      :title="isEdit ? '编辑角色' : '新增角色'"
      width="600px"
      :before-close="handleCloseEdit"
    >
      <el-form
        ref="editFormRef"
        :model="editForm"
        :rules="editRules"
        label-width="80px"
      >
        <el-form-item label="角色名称" prop="name">
          <el-input v-model="editForm.name" placeholder="请输入角色名称" />
        </el-form-item>
        <el-form-item label="描述" prop="description">
          <el-input
            v-model="editForm.description"
            type="textarea"
            :rows="3"
            placeholder="请输入角色描述"
          />
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-radio-group v-model="editForm.status">
            <el-radio value="active">启用</el-radio>
            <el-radio value="inactive">禁用</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>

      <template #footer>
        <span class="dialog-footer">
          <el-button @click="editVisible = false">取消</el-button>
          <el-button type="primary" :loading="submitLoading" @click="handleSubmit">
            {{ submitLoading ? '保存中...' : '保存' }}
          </el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 权限配置对话框 -->
    <el-dialog
      v-model="permissionVisible"
      title="权限配置"
      width="800px"
      :before-close="handleClosePermission"
    >
      <div v-if="currentRole" class="permission-config">
        <div class="role-info">
          <h3>{{ currentRole.name }}</h3>
          <p>{{ currentRole.description }}</p>
        </div>

        <el-divider />

        <div class="permission-tree-container">
          <div class="tree-header">
            <span>权限列表</span>
            <div class="tree-actions">
              <el-button size="small" @click="expandAll">展开全部</el-button>
              <el-button size="small" @click="collapseAll">收起全部</el-button>
              <el-button size="small" @click="checkAll">全选</el-button>
              <el-button size="small" @click="uncheckAll">取消全选</el-button>
            </div>
          </div>

          <el-tree
            ref="permissionTreeRef"
            :data="permissionTree"
            :props="{ children: 'children', label: 'name' }"
            :default-checked-keys="selectedPermissions"
            node-key="id"
            show-checkbox
            check-strictly
            class="permission-tree"
            @check="handlePermissionCheck"
          />
        </div>
      </div>

      <template #footer>
        <span class="dialog-footer">
          <el-button @click="permissionVisible = false">取消</el-button>
          <el-button type="primary" :loading="permissionLoading" @click="handleSavePermissions">
            {{ permissionLoading ? '保存中...' : '保存权限' }}
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox, type FormInstance, type FormRules } from 'element-plus'
import {
  Plus,
  Search,
  Refresh,
  Delete,
  Download,
  View,
  Edit,
  Setting
} from '@element-plus/icons-vue'
import { rolesApi, permissionsApi } from '@/api'
import type { Role, Permission } from '@/api'

// 响应式数据
const loading = ref(false)
const submitLoading = ref(false)
const permissionLoading = ref(false)
const detailVisible = ref(false)
const editVisible = ref(false)
const permissionVisible = ref(false)
const isEdit = ref(false)
const selectedRoles = ref([])
const currentRole = ref(null)
const selectedPermissions = ref([])

const tableRef = ref<any>()
const editFormRef = ref<FormInstance>()
const permissionTreeRef = ref<any>()

// 搜索表单
const searchForm = reactive({
  name: '',
  status: ''
})

// 编辑表单
const editForm = reactive({
  id: '',
  name: '',
  description: '',
  status: 'active'
})

// 分页
const pagination = reactive({
  page: 1,
  size: 20,
  total: 0
})

// 角色列表
const roles = ref([
  {
    id: 1,
    name: '超级管理员',
    description: '拥有系统所有权限',
    status: 'active',
    permissions: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10],
    user_count: 1,
    created_at: '2024-01-01 00:00:00'
  },
  {
    id: 2,
    name: '编辑者',
    description: '可以编辑内容和管理用户',
    status: 'active',
    permissions: [1, 2, 3, 4, 5],
    user_count: 3,
    created_at: '2024-01-02 00:00:00'
  },
  {
    id: 3,
    name: '查看者',
    description: '只能查看内容',
    status: 'active',
    permissions: [1, 2],
    user_count: 5,
    created_at: '2024-01-03 00:00:00'
  }
])

// 权限树
const permissionTree = ref([
  {
    id: 1,
    name: '系统管理',
    children: [
      { id: 2, name: '用户管理' },
      { id: 3, name: '角色管理' },
      { id: 4, name: '权限管理' }
    ]
  },
  {
    id: 5,
    name: '内容管理',
    children: [
      { id: 6, name: '文章管理' },
      { id: 7, name: '分类管理' },
      { id: 8, name: '标签管理' }
    ]
  },
  {
    id: 9,
    name: '系统设置',
    children: [
      { id: 10, name: '基础设置' },
      { id: 11, name: '邮件设置' },
      { id: 12, name: '存储设置' }
    ]
  }
])

// 表单验证规则
const editRules: FormRules = {
  name: [
    { required: true, message: '请输入角色名称', trigger: 'blur' },
    { min: 2, max: 20, message: '角色名称长度在 2 到 20 个字符', trigger: 'blur' }
  ],
  description: [
    { max: 200, message: '描述不能超过 200 个字符', trigger: 'blur' }
  ]
}

// 方法
const handleSearch = () => {
  pagination.page = 1
  loadRoles()
}

const handleReset = () => {
  Object.assign(searchForm, {
    name: '',
    status: ''
  })
  handleSearch()
}

const handleCreate = () => {
  isEdit.value = false
  editVisible.value = true
  resetEditForm()
}

const handleView = (row: any) => {
  currentRole.value = row
  detailVisible.value = true
}

const handleEdit = (row: any) => {
  isEdit.value = true
  editVisible.value = true
  Object.assign(editForm, {
    id: row.id,
    name: row.name,
    description: row.description,
    status: row.status
  })
}

const handlePermissions = (row: any) => {
  currentRole.value = row
  selectedPermissions.value = [...row.permissions]
  permissionVisible.value = true
}

const handleDelete = async (row: any) => {
  try {
    await ElMessageBox.confirm(
      `确定要删除角色 "${row.name}" 吗？`,
      '删除确认',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    // 这里调用删除API
    ElMessage.success('删除成功')
    loadRoles()
  } catch {
    // 用户取消删除
  }
}

const handleBatchDelete = async () => {
  if (!selectedRoles.value.length) {
    ElMessage.warning('请选择要删除的角色')
    return
  }

  try {
    await ElMessageBox.confirm(
      `确定要删除选中的 ${selectedRoles.value.length} 个角色吗？`,
      '批量删除确认',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    // 这里调用批量删除API
    ElMessage.success('批量删除成功')
    selectedRoles.value = []
    loadRoles()
  } catch {
    // 用户取消删除
  }
}

const handleStatusChange = async (row: any) => {
  try {
    // 这里调用状态更新API
    ElMessage.success(`角色状态已${row.status === 'active' ? '启用' : '禁用'}`)
  } catch (error) {
    // 恢复原状态
    row.status = row.status === 'active' ? 'inactive' : 'active'
    ElMessage.error('状态更新失败')
  }
}

const handleExport = () => {
  ElMessage.info('导出功能开发中...')
}

const handleSelectionChange = (selection: any[]) => {
  selectedRoles.value = selection
}

const handleSizeChange = (size: number) => {
  pagination.size = size
  loadRoles()
}

const handlePageChange = (page: number) => {
  pagination.page = page
  loadRoles()
}

const handleSubmit = async () => {
  if (!editFormRef.value) return

  await editFormRef.value.validate(async (valid) => {
    if (valid) {
      submitLoading.value = true
      try {
        // 这里调用保存API
        await new Promise(resolve => setTimeout(resolve, 1000)) // 模拟API调用
        
        ElMessage.success(isEdit.value ? '更新成功' : '创建成功')
        editVisible.value = false
        loadRoles()
      } catch (error) {
        ElMessage.error(isEdit.value ? '更新失败' : '创建失败')
      } finally {
        submitLoading.value = false
      }
    }
  })
}

const handleCloseDetail = () => {
  detailVisible.value = false
  currentRole.value = null
}

const handleCloseEdit = () => {
  editFormRef.value?.resetFields()
  editVisible.value = false
  resetEditForm()
}

const handleClosePermission = () => {
  permissionVisible.value = false
  currentRole.value = null
  selectedPermissions.value = []
}

const resetEditForm = () => {
  Object.assign(editForm, {
    id: '',
    name: '',
    description: '',
    status: 'active'
  })
}

const loadRoles = async () => {
  loading.value = true
  try {
    // 这里调用角色列表API
    await new Promise(resolve => setTimeout(resolve, 500)) // 模拟API调用
    pagination.total = roles.value.length
  } catch (error) {
    ElMessage.error('加载角色列表失败')
  } finally {
    loading.value = false
  }
}

const formatTime = (time: string) => {
  if (!time) return '-'
  return new Date(time).toLocaleString('zh-CN')
}

// 权限树操作
const expandAll = () => {
  const tree = permissionTreeRef.value
  if (tree) {
    const allKeys = getAllNodeKeys(permissionTree.value)
    allKeys.forEach(key => tree.store.nodesMap[key].expanded = true)
  }
}

const collapseAll = () => {
  const tree = permissionTreeRef.value
  if (tree) {
    const allKeys = getAllNodeKeys(permissionTree.value)
    allKeys.forEach(key => tree.store.nodesMap[key].expanded = false)
  }
}

const checkAll = () => {
  const tree = permissionTreeRef.value
  if (tree) {
    const allKeys = getAllNodeKeys(permissionTree.value)
    tree.setCheckedKeys(allKeys)
    selectedPermissions.value = allKeys
  }
}

const uncheckAll = () => {
  const tree = permissionTreeRef.value
  if (tree) {
    tree.setCheckedKeys([])
    selectedPermissions.value = []
  }
}

const getAllNodeKeys = (nodes: any[]): number[] => {
  const keys: number[] = []
  const traverse = (nodeList: any[]) => {
    nodeList.forEach(node => {
      keys.push(node.id)
      if (node.children && node.children.length > 0) {
        traverse(node.children)
      }
    })
  }
  traverse(nodes)
  return keys
}

const handlePermissionCheck = (data: any, checked: any) => {
  selectedPermissions.value = checked.checkedKeys
}

const handleSavePermissions = async () => {
  permissionLoading.value = true
  try {
    // 这里调用保存权限API
    await new Promise(resolve => setTimeout(resolve, 1000)) // 模拟API调用
    
    // 更新当前角色的权限
    if (currentRole.value) {
      currentRole.value.permissions = [...selectedPermissions.value]
      const roleIndex = roles.value.findIndex(r => r.id === currentRole.value.id)
      if (roleIndex > -1) {
        roles.value[roleIndex].permissions = [...selectedPermissions.value]
      }
    }
    
    ElMessage.success('权限配置保存成功')
    permissionVisible.value = false
  } catch (error) {
    ElMessage.error('权限配置保存失败')
  } finally {
    permissionLoading.value = false
  }
}

// 组件挂载时加载数据
onMounted(() => {
  loadRoles()
})
</script>

<style scoped>
.roles-page {
  padding: 20px;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  margin-bottom: 20px;
}

.header-left h1 {
  margin: 0 0 8px 0;
  font-size: 24px;
  font-weight: 600;
  color: #303133;
}

.header-left p {
  margin: 0;
  color: #606266;
  font-size: 14px;
}

.search-card {
  margin-bottom: 20px;
}

.search-form {
  margin-bottom: 0;
}

.table-card {
  margin-bottom: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.header-actions {
  display: flex;
  gap: 8px;
}

.pagination-container {
  display: flex;
  justify-content: center;
  margin-top: 20px;
}

.role-detail {
  padding: 20px 0;
}

.permissions-section {
  margin-top: 30px;
}

.permissions-section h3 {
  margin: 0 0 16px 0;
  font-size: 16px;
  font-weight: 600;
  color: #303133;
}

.permission-tree {
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  padding: 10px;
  max-height: 300px;
  overflow-y: auto;
}

.permission-config {
  padding: 10px 0;
}

.role-info h3 {
  margin: 0 0 8px 0;
  font-size: 18px;
  font-weight: 600;
  color: #303133;
}

.role-info p {
  margin: 0;
  color: #606266;
  font-size: 14px;
}

.permission-tree-container {
  margin-top: 20px;
}

.tree-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 16px;
}

.tree-header span {
  font-size: 16px;
  font-weight: 600;
  color: #303133;
}

.tree-actions {
  display: flex;
  gap: 8px;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}

@media (max-width: 768px) {
  .roles-page {
    padding: 12px;
  }
  
  .page-header {
    flex-direction: column;
    gap: 16px;
  }
  
  .search-form {
    flex-direction: column;
  }
  
  .search-form .el-form-item {
    margin-right: 0;
    margin-bottom: 16px;
  }
  
  .header-actions {
    flex-direction: column;
    width: 100%;
  }
  
  .tree-header {
    flex-direction: column;
    gap: 12px;
    align-items: flex-start;
  }
  
  .tree-actions {
    flex-wrap: wrap;
    width: 100%;
  }
}
</style>